// pagesCollect/pages/collect/edit/villageEdit.js
import { getVillageMsg, updateVillageMsg } from "../../../../../api/collect"
import { getStorage } from "../../../../../utils/localStorage"

const app = getApp()

const rules = [{ key: 'villageIntroduce', msg: '请填写乡村简介' },
{ key: 'address', msg: '请输入乡村地址' },
{ key: 'longitude', msg: '请选择乡村定位' },
{ key: 'villageImage', msg: '请上传乡村图片' },
{ key: 'parkLongitude', msg: '请选择停车场定位' }]

Page({
  data: {
    navData: {
      title: '乡村数据完善',
      level: 10
    },
    id: '',
    form: {},
    navHeight: 32,
    navTop: 48,
    position: {},
    parkPosition: {},
    villageImageStr: '',
  },
  onLoad(e) {
    this.setData({
      navHeight: app.globalData.navHeight, //导航栏高度
      navTop: app.globalData.navTop, //导航栏距顶部距离
    });
    this.data.id = e.id;
    this.getVillage()
  },
  getVillage() {
    getVillageMsg({ villageId: this.data.id }).then(res => {
      // console.log(res)
      this.setData({
        ['navData.title']:res.data.data.villageName+'数据完善',
        form: res.data.data,
        position: {
          longitude: res.data.data.longitude,
          latitude: res.data.data.latitude
        },
        parkPosition: {
          longitude: res.data.data.parkLongitude,
          latitude: res.data.data.parkLatitude
        },
        villageImageStr: res.data.data.villageImage
      })
    })
  },
  submit() {
    let sendData = JSON.parse(JSON.stringify(this.data.form));
    let errMsg = null;
    for (let i = 0; i < rules.length; i++) {
      let key = rules[i].key;
      if (!sendData[key]) {
        errMsg = rules[i].msg;
        break;
      }
    }
    if (errMsg) {
      wx.showToast({
        icon: 'none',
        title: errMsg,
      })
      return false;
    }
    let userinfo = getStorage('user')
    sendData.userId = userinfo.id;
    updateVillageMsg(sendData).then(res => {
      let pages = getCurrentPages();
      let prePage = pages[pages.length - 2];
      prePage.refresh()
      wx.showModal({
        content: '提交成功',
        showCancel:false,
        complete: (res) => {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
    })
  },
  toEdit() {
    app.globalData.introduceStr = this.data.form.villageIntroduce;
    wx.navigateTo({
      url: '/pagesCollect/pages/collect/edit/editor/editor?key=villageIntroduce',
    })
  },
  dwChg(e) {
    let {
      longitude,
      latitude
    } = e.detail
    this.setData({
      ['form.longitude']: longitude,
      ['form.latitude']: latitude
    })
  },
  tccChg(e) {
    let {
      longitude,
      latitude
    } = e.detail
    this.setData({
      ['form.parkLongitude']: longitude,
      ['form.parkLatitude']: latitude
    })
  },
  villageImageChg(e) {
    this.setData({
      ['form.villageImage']: e.detail,
    })
  },
})